package com.recharge.web.handler;

import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.result.web.ObjectResponse;
import com.recharge.domain.UserLoginDO;
import com.recharge.service.UserLoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;



@Component
public class UserLoginHandler {

    @Autowired
    private UserLoginService userLoginService;

    public Mono<ServerResponse> register(ServerRequest request) {
        Mono<UserLoginDO> domain = request.bodyToMono(UserLoginDO.class);
        Mono<ResultDO> result = userLoginService.add(domain);
        return result.flatMap(res ->{
            ObjectResponse response = new ObjectResponse();
            if(!res.isSuccess()) {
                response.setStatus(res.getErrorCode().getCode());
                response.setMsg(res.getErrorCode().getMsg());
            }
            return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(Mono.just(response), ObjectResponse.class);
        });

    }

    public Mono<ServerResponse> login(ServerRequest request) {
        Mono<UserLoginDO> domain = request.bodyToMono(UserLoginDO.class);
        return domain.flatMap(userLoginDO -> {
            Subject subject = SecurityUtils.getSubject();
            // 在认证提交前准备 token（令牌）
            UsernamePasswordToken token = new UsernamePasswordToken(userLoginDO.getUsername(), userLoginDO.getPassword());
            ObjectResponse response = new ObjectResponse();
            if (subject.isAuthenticated()) {
                response.setMsg("登陆成功");
            } else {
                token.clear();
                response.setMsg("登录失败");
            }
            return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(Mono.just(response), ObjectResponse.class);
        });
    }
}
